/**
 * CustomerDAO.java
 *
 * $Id$
 *
 */
package dao;

import bean.Customer;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 * 
 * @author Dyego Souza do Carmo
 * @since 
 */
public class CustomerDAO extends GenericDAO {

    private static final long serialVersionUID = 1L;

    
    /**
     * Construtor padrão
     *
     * @author Dyego Souza do Carmo
     * @version 1.0, 
     */
    public CustomerDAO(){
    }

    public int addCustomer(Customer ctm) throws SQLException {
        ctm.setId(getNextId("CUSTOMERS"));
        String query = "INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,TELEPHONE) VALUES (?,?,?,?,?)";
        executeCommand(query, ctm.getId(),ctm.getName(),ctm.getAge(),ctm.getAddress(),ctm.getTelephone());
        return ctm.getId();
    }

    public void removeCustomer(int idCustomer) throws SQLException {
        executeCommand("DELETE FROM CUSTOMERS WHERE ID = ?", idCustomer);
    }

    public void updateCustomer(Customer ctm) throws SQLException {
        String query = "UPDATE CUSTOMERS SET NAME = ?, AGE = ?, ADDRESS = ?, TELEPHONE = ? WHERE ID = ?";
        executeCommand(query, ctm.getName(),ctm.getAge(),ctm.getAddress(),ctm.getTelephone(),ctm.getId());
    }

    public Customer getCustomer(int idCustomer) throws SQLException {
        ResultSet rs = executeQuery("SELECT * FROM CUSTOMERS WHERE ID = ?", idCustomer);
        Customer ctm = null;
        if (rs.next()) {
            ctm = populateCustomer(rs);
        }
        rs.close();
        return ctm;
    }

    public List<Customer> getAllCustomers() throws SQLException {
        ResultSet rs = executeQuery("SELECT * FROM CUSTOMERS");
        List<Customer> toReturn = new LinkedList<Customer>();
        while (rs.next()) {
            toReturn.add(populateCustomer(rs));
        }
        rs.close();
        return toReturn;

    }

    public static Customer populateCustomer(ResultSet rs) throws SQLException {
        Customer toReturn = new Customer();
        toReturn.setId(rs.getInt("ID"));
        toReturn.setName(rs.getString("NAME"));
        toReturn.setAge(rs.getInt("AGE"));
        toReturn.setAddress(rs.getString("ADDRESS"));
        toReturn.setTelephone(rs.getString("TELEPHONE"));
        return toReturn;
    }

    public List<Customer> getCustomersByName(String name) throws SQLException {
        List<Customer> toReturn = new LinkedList<Customer>();
        ResultSet rs = executeQuery("SELECT * FROM CUSTOMERS WHERE NAME LIKE ?", "%"+name+"%");
        while (rs.next()) {
            toReturn.add(populateCustomer(rs));
        }
        rs.close();
        return toReturn;
    }

}
